package org.mspring.platform.security.service;

import java.util.List;

import org.mspring.platform.security.dao.TreeItemDao;
import org.mspring.platform.security.entity.TreeItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Gao Youbo
 * @since 2012-7-16
 */
@Service
@Transactional
public class TreeItemService {

    @Autowired
    private TreeItemDao treeItemDao;

    public String create(TreeItem treeItem) {
        return treeItemDao.insert(treeItem);
    }

    public void clear() {
        treeItemDao.clear();
    }

    public List<TreeItem> listAll() {
        return treeItemDao.listAll();
    }

    public List<TreeItem> listByRole(long roleId) {
        return treeItemDao.listByRole(roleId);
    }

    public TreeItem get(String id) {
        return treeItemDao.get(id);
    }

    /**
     * 加载树形菜单，Type为TreeItem.Type.TREE_FOLDER, TreeItem.Type.TREE_ITEM
     *
     * @param userId
     * @return
     */
    public List<TreeItem> listTreeByUser(long userId) {
        return treeItemDao.listTreeByUser(userId);
    }

    /**
     * 加载tab页签
     *
     * @param parent
     *            父节点编号
     * @param userId
     *            用户编号
     * @return
     */
    public List<TreeItem> listTabByUser(String parent, long userId) {
        return treeItemDao.listTabByUser(parent, userId);
    }

    /**
     * 加载树形菜单节点
     *
     * @param parent
     *            父节点编号
     * @param userId
     *            用户编号
     * @return
     */
    public TreeItem getOpenTab(String parent, long userId) {
        List<TreeItem> openTabs = treeItemDao.listOpenTabByUser(parent, userId);
        if (openTabs != null && !openTabs.isEmpty()) {
            return openTabs.get(0);
        }
        openTabs = treeItemDao.listTabByUser(parent, userId);
        if (openTabs != null && !openTabs.isEmpty()) {
            return openTabs.get(0);
        }
        return null;
    }

}
